package com.crm.dao.impl;

import java.util.List;
import java.util.Map;

import com.crm.dao.SaleVisitDao;
import com.crm.pojo.PageInfo;
import com.crm.pojo.SaleVisit;
import com.crm.util.JdbcUtil;

public class SaleVisitDaoImpl implements SaleVisitDao {

	@Override
	public int insertVisit(SaleVisit visit) {
		String sql = "insert into sale_visit values(null,?,?,?,?,?,?,?);";
		Integer visitCustId = visit.getVisitCustId();
		Integer visitUserId = visit.getVisitUserId();
		String date = visit.getDate();
		String visitInterviewee = visit.getVisitInterviewee();
		String visitAddr = visit.getVisitAddr();
		String visitDetail = visit.getVisitDetail();
		String visitNexttime = visit.getVisitNexttime();
		return JdbcUtil.executeUpdate(sql, visitCustId, visitUserId, date, visitInterviewee, visitAddr, visitDetail, visitNexttime);
	}

	@Override
	public PageInfo queryVisit(String custName, Integer pageSize, Integer pageNumber) {
		PageInfo page = new PageInfo();
		page.setPageSize(pageSize);
		page.setPageNumber(pageNumber);
		String sql = "select * from sale_visit v left join cst_customer c on v.visit_cust_id=c.cust_id left join cst_linkman l on v.visit_user_id=l.lkm_id where 1=1";
		if(custName!=null && !"".equals(custName)) {
			sql += " and cust_name like '%"+custName+"%'";
		}
		page.setTotalCount(getTotalCount(sql));
		sql += " limit "+(pageNumber-1)*pageSize+","+pageSize;
		List<Map> linkmans = JdbcUtil.executeQuery(sql, null);
		page.setResult(linkmans);
		return page;
	}
	private Integer getTotalCount(String sql) {
		String newSql = "select count(*) from ("+sql+") c";
		List<Map> linkmans = JdbcUtil.executeQuery(newSql, null);
		String linkman = "";
		for(Map l:linkmans) {
			linkman = l.get("count(*)").toString();
		}
		return Integer.parseInt(linkman);
	}

	@Override
	public int delete(Integer visitId) {
		String sql = "delete from sale_visit where visit_id=?";
		return JdbcUtil.executeUpdate(sql, visitId);
	}

	@Override
	public List<Map> queryVisitById(Integer visitId) {
		String sql = "select * from sale_visit where visit_id=?";
		return JdbcUtil.executeQuery(sql, visitId);
	}

	@Override
	public int updateVisit(SaleVisit visit) {
		String sql = "update sale_visit set visit_cust_id=?,visit_user_id=?,visit_time=?,visit_interviewee=?,visit_addr=?,visit_detail=?,visit_nexttime=? where visit_id=?";
		Integer visitCustId = visit.getVisitCustId();
		Integer visitUserId = visit.getVisitUserId();
		String date = visit.getDate();
		String visitInterviewee = visit.getVisitInterviewee();
		String visitAddr = visit.getVisitAddr();
		String visitDetail = visit.getVisitDetail();
		String visitNexttime = visit.getVisitNexttime();
		Integer visitId = visit.getVisitId();
		return JdbcUtil.executeUpdate(sql, visitCustId, visitUserId, date, visitInterviewee, visitAddr, visitDetail, visitNexttime, visitId);
	}

}
